<?php
namespace app\index\controller;
use think\Controller;
use think\Config;

class Collect extends Controller {

	public function CollectFood() {
		$data = array(
			'food_id' => $_POST['food_id'],
			'openid' => $_POST['openid']
		);
		$collectFood = model('CollectFood');
		$food = model('Food')->where('id', $_POST['food_id'])->find();
		$res = array('code' => 0);
		if ($collectFood->where($data)->find()) {
			// 查找到证明已经收藏，二次点击表示取消收藏
			if ($collectFood->where($data)->delete()) {
				$res['code'] = 2;
				model('Food')->save(['collect_num' => $food->collect_num - 1], ['id' => $_POST['food_id']]);
			}
		} else {
			$collectFood->data($data);
			if ($collectFood->save()) {
				$res['code'] = 1;
				model('Food')->save(['collect_num' => $food->collect_num + 1], ['id' => $_POST['food_id']]);
			}
		}
		echo json_encode($res);
		exit();
	}


	public function CollectShop() {
		$shopId = $_POST['shop_id'];
		$openid = $_POST['openid'];
		$data = array(
			'shop_id' => $shopId,
			'openid' => $openid
		);
		$collectShop = model('CollectShop');
		$shop = model('Shop')->where('id', $shopId)->find();
		$res = array('code' => 0);
		if ($collectShop->where($data)->find()) {
			if ($collectShop->where($data)->delete()) {
				$res['code'] = 2;
				model('Shop')->save(['collect_num' => $shop->collect_num - 1], ['id' => $shopId]);
			}
		} else {
			$collectShop->data($data);
			if ($collectShop->save()) {
				$res['code'] = 1;
				model('Shop')->save(['collect_num' => $shop->collect_num + 1], ['id' => $shopId]);
			}
		}
		echo json_encode($res);
		exit();
	}

	public function GetAllCollectShops() {
		$openid = $_POST['openid'];
		$shopCollects = model('CollectShop')->where('openid', $openid)->select();
		$res = array();
		for ($i = 0, $count = count($shopCollects); $i < $count; $i++) {
			$shopId = $shopCollects[$i]['shop_id'];
			$shop = model('Shop')->where('id', $shopId)->find();

			$foodNum = model('Food')->where('shop_id', $shopId)->count();
			$shop['food_num'] = $foodNum;
			$shop['is_collect'] = 2;

			array_push($res, $shop);
		}
		echo json_encode($res);
		exit();
	}


	public function GetAllCollectFoods() {
		$openid = $_POST['openid'];
		$collectFoods = model('CollectFood')->where('openid', $openid)->select();
		$res = array();
		for ($i = 0, $count = count($collectFoods); $i < $count; $i++) {
			$foodId = $collectFoods[$i]['food_id'];
			$food = model('Food')->where('id', $foodId)->find();

			$shopId = $food['shop_id'];
			$shopInfo = model('Shop')->where('id', $shopId)->find();
			$food['shop_name'] = $shopInfo->shop_name;
			$food['logo_url'] = $shopInfo->logo_url;
			$food['is_collect'] = 2;

			array_push($res, $food);
		}
		echo json_encode($res);
		exit();
	}




}